<template>
  <view class="filter-page">
    <!-- 顶部导航栏 -->
    <view class="top-bar">
      <text class="nav-btn cancel" @click="back">取消</text>
      <text class="nav-title">职位筛选</text>
      <text class="nav-btn confirm" @click="submitRecruitInfoVO">确认</text>
    </view>

    <!-- 主体内容区（左右布局） -->
    <view class="content-container">
      <!-- 左侧筛选列表 -->
      <view class="left-panel">
        <view 
          v-for="(item, index) in filterItems" 
          :key="index"
          class="filter-item" 
          :class="{ 
            'required': item.required, 
            'selected': currentTab === index 
          }"
          @click="switchTab(index)">
          <text class="item-label">{{ item.label }}</text>
        </view>
      </view>

      <!-- 右侧内容区（动态切换） -->
      <view class="right-panel">
        <!-- 公司行业选择（字符串value，选择时转数字） -->
            <template v-if="currentTab === 0">
              <checkbox-group @change="handleIndustryChange">
                <label class="option-item" v-for="(option, i) in industryOptions" :key="i">
                  <checkbox 
                    :value="String(option.industryId)" 
                    :checked="RecruitInfoVO.industryId.includes(option.industryId)" 
                  />
                  <text>{{ option.industryName }}</text>
                </label>
              </checkbox-group>
            </template>

         <!-- 职位类型选择（单选，字符串value转数字） -->
            <template v-else-if="currentTab === 1">
              <radio-group @change="handlePositionTypeChange">
                <label class="option-item" v-for="(option, i) in positionTypeOptions" :key="i">
                  <radio 
                    :value="String(option.typeId)" 
                    :checked="RecruitInfoVO.jobTypeId === option.typeId" 
                  />
                  <text>{{ option.typeName }}</text>
                </label>
              </radio-group>
            </template>

        <!-- 职位选择 -->
		
        <template v-else-if="currentTab === 2">
          <view v-if="RecruitInfoVO.jobTypeId">
            <checkbox-group @change="handlePositionChange">
              <label class="option-item" v-for="(option, i) in positionOptions" :key="i">
                <checkbox 
                  :value="String(option.jobId)" 
                  :checked="RecruitInfoVO.jobId.includes(option.jobId)" 
                />
                <text>{{ option.jobName }}</text>
              </label>
            </checkbox-group>
          </view>
          <view v-else class="hint-message">
            <text>请先选择职位类型</text>
          </view>
        </template>

        <!-- 薪资范围 -->
        <template v-else-if="currentTab === 3">
          <view class="salary-range-container">
            <view class="salary-input-group" :class="{ 'error': isSalaryInvalid }">
              <input 
                type="number" 
                class="salary-input" 
                placeholder="最低薪资" 
                v-model="RecruitInfoVO.startSalary"
                @input="validateSalary"
              />
              <text class="unit">元/月</text>
            </view>
            <view class="salary-input-group" :class="{ 'error': isSalaryInvalid }">
              <input 
                type="number" 
                class="salary-input" 
                placeholder="最高薪资" 
                v-model="RecruitInfoVO.maxSalary"
                @input="validateSalary"
              />
              <text class="unit">元/月</text>
            </view>
            <text v-if="isSalaryInvalid" class="error-message">最低薪资不能高于最高薪资</text>
          </view>
        </template>

        <!-- 工资形式选择（同行业选择逻辑） -->
            <template v-else-if="currentTab === 4">
              <checkbox-group @change="handlePayMethodChange">
                <label class="option-item" v-for="(option, i) in paymentTypeOptions" :key="i">
                  <checkbox :value="option.value" :checked="RecruitInfoVO.payMethod.includes(Number(option.value))" />
                  <text>{{ option.label }}</text>
                </label>
              </checkbox-group>
            </template>

        <!-- 公司资质选择 -->
        <template v-else-if="currentTab === 5">
          <checkbox-group @change="(e) => RecruitInfoVO.companyType = e.detail.value">
            <label class="option-item" v-for="(option, i) in qualificationOptions" :key="i">
              <checkbox :value="option.value" :checked="RecruitInfoVO.companyType.includes(option.value)" />
              <text>{{ option.label }}</text>
            </label>
          </checkbox-group>
        </template>

        <!-- 公司规模选择 -->
        <template v-else-if="currentTab === 6">
          <checkbox-group @change="(e) => RecruitInfoVO.companySize = e.detail.value">
            <label class="option-item" v-for="(option, i) in companySizeOptions" :key="i">
              <checkbox :value="option.value" :checked="RecruitInfoVO.companySize.includes(option.value)" />
              <text>{{ option.label }}</text>
            </label>
          </checkbox-group>
        </template>
      </view>
    </view>
  </view>
</template>

<script>
	import {getPositionTypeAndFirst,getJobsByTypeId} from '@/api/user.js'
export default {
  data() {
    return {
      currentTab: 0,
	  nowJobTypeId: null,
      isSalaryInvalid: false,
      filterItems: [
        { label: '公司行业:', required: false },
        { label: '职位类型:', required: false },
        { label: '职位:', required: false },
        { label: '薪资范围(月):', required: true },
        { label: '工资形式:', required: false },
        { label: '公司资质:', required: false },
        { label: '公司规模:', required: false }
      ],
      industryOptions: [],
            positionTypeOptions: [],
            positionOptions: [],
            paymentTypeOptions: [
              { value: '2', label: '月薪' },
              { value: '1', label: '周薪' },
              { value: '0', label: '日薪' },
              { value: '3', label: '时薪' },
              { value: '4', label: '面议' }
            ],
            qualificationOptions: [
              { value: '上市', label: '上市' },
              { value: '国企', label: '国企' },
              { value: '外企', label: '外企' }
            ],
            companySizeOptions: [
              { value: '20人以下', label: '20人以下' },
              { value: '20~99人', label: '20~99人' },
              { value: '99~300人', label: '99~300人' },
              { value: '300人以上', label: '300人以上' }
            ],
      RecruitInfoVO: {
        industryId: [],
        jobId: [],
        startSalary: null,
        maxSalary: null,
        payMethod: [],
        companyType: [],
        companySize: [],
        regionId: null,
		jobTypeId: null,
      }
    }
  },
  onLoad() {
	const cachedRecruitInfo = uni.getStorageSync("RecruitInfoVO") || {};
	  
	  // 2. 对数组字段补充默认值：若缓存中字段为 undefined，用空数组替代
	  this.RecruitInfoVO = {
	    // 基础字段：从缓存读取，无则用初始值
	    industryId: cachedRecruitInfo.industryId || [],  // 确保是数组
	    jobId: cachedRecruitInfo.jobId || [],            // 确保是数组
	    payMethod: cachedRecruitInfo.payMethod || [],    // 确保是数组
	    companyType: cachedRecruitInfo.companyType || [],// 补充：避免后续扩展时出错
	    companySize: cachedRecruitInfo.companySize || [],// 补充：避免后续扩展时出错
	    // 非数组字段：从缓存读取，无则用初始值
	    startSalary: cachedRecruitInfo.startSalary || null,
	    maxSalary: cachedRecruitInfo.maxSalary || null,
	    regionId: cachedRecruitInfo.regionId || null,
	    jobTypeId: cachedRecruitInfo.jobTypeId || null,
	  };

	getPositionTypeAndFirst().then(res=>{
		this.positionTypeOptions = res.data.jobTypeDOS
		this.industryOptions = res.data.industryDOS
	})
  },
  methods: {
    switchTab(index) {
      this.currentTab = index
	  if(index === 2) {
	        this.loadPositionOptions();
	      }
    },
    // 公司行业选择：字符串value转数字存入
        handleIndustryChange(e) {
            this.RecruitInfoVO.industryId = e.detail.value.map(Number);
          },
    
        // 职位类型选择：字符串value转数字存入
        handlePositionTypeChange(e) {
    this.RecruitInfoVO.jobTypeId = Number(e.detail.value);
    this.RecruitInfoVO.jobId = [];
    // 立即加载职位选项
    if(this.currentTab === 2) {
      this.loadPositionOptions();
    }
  },
    
        // 职位选择：字符串value转数字存入
        handlePositionChange(e) {
            this.RecruitInfoVO.jobId = e.detail.value.map(Number);
          },
    
        // 工资形式选择：字符串value转数字存入
        handlePayMethodChange(e) {
          this.RecruitInfoVO.payMethod = e.detail.value.map(Number);
        },
		
		loadPositionOptions() {
		    if(this.RecruitInfoVO.jobTypeId && this.nowJobTypeId !== this.RecruitInfoVO.jobTypeId) {
		      getJobsByTypeId({jobTypeId: this.RecruitInfoVO.jobTypeId}).then(res => {
		        this.positionOptions = res.data;
		        this.nowJobTypeId = this.RecruitInfoVO.jobTypeId;
		      });
		    }
		  },
    
    validateSalary() {
      const { startSalary, maxSalary } = this.RecruitInfoVO
      this.isSalaryInvalid = startSalary && maxSalary && +startSalary > +maxSalary
      if (this.isSalaryInvalid) {
        uni.showToast({ title: '最低薪资不能高于最高薪资', icon: 'none' })
      }
    },
    
    submitRecruitInfoVO() {
      if (this.isSalaryInvalid) {
        uni.showToast({ title: '请修正薪资范围', icon: 'none' })
        return
      }
      uni.setStorageSync("RecruitInfoVO",this.RecruitInfoVO);
	  uni.reLaunch({
	      url: '/pages/zcy/main'
	    })
    },
    
    
    back() {
      uni.navigateBack()
    }
  }
}
</script>

<style scoped>
.filter-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #fff;
}

.top-bar {
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 32rpx;
  border-bottom: 1px solid #eee;
}

.nav-btn {
  font-size: 28rpx;
  color: #007aff;
}

.nav-title {
  font-size: 32rpx;
  font-weight: bold;
}

.content-container {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.left-panel {
  width: 300rpx;
  border-right: 1px solid #eee;
  padding: 20rpx;
}

.filter-item {
  margin-bottom: 24rpx;
  font-size: 28rpx;
  line-height: 44rpx;
  padding: 8rpx 12rpx;
  border-radius: 8rpx;
  transition: background-color 0.3s;
}

.filter-item:active {
  background-color: #f9f9f9;
}

.filter-item.required .item-label::before {
  content: "*";
  color: red;
  margin-right: 4rpx;
}

.filter-item.selected {
  background-color: #f5f5f5;
  font-weight: bold;
}

.item-label {
  color: #666;
}

.filter-item.selected .item-label {
  color: #333;
}

.right-panel {
  flex: 1;
  padding: 20rpx 32rpx;
  background-color: #f9f9f9;
  overflow-y: auto;
}

.option-item {
  display: flex;
  align-items: center;
  margin-bottom: 28rpx;
  padding: 16rpx 0;
  font-size: 28rpx;
}

.hint-message {
  padding: 20rpx;
  color: #999;
  font-size: 28rpx;
  text-align: center;
}

.salary-range-container {
  margin-top: 20rpx;
}

.salary-input-group {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
  padding: 20rpx;
  background-color: #fff;
  border-radius: 8rpx;
  border: 1rpx solid #eee;
}

.salary-input-group.error {
  border-color: #ff4d4f;
}

.salary-input {
  flex: 1;
  height: 40rpx;
  font-size: 28rpx;
  color: #333;
}

.unit {
  font-size: 24rpx;
  color: #999;
  margin-left: 10rpx;
}

.error-message {
  color: #ff4d4f;
  font-size: 24rpx;
  margin-top: 10rpx;
}

radio, checkbox {
  margin-right: 16rpx;
  transform: scale(0.9);
}
</style>